﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using NVelocity;
using NVelocity.App;
using NVelocity.Runtime;
using NVelocity.Context;
using LearnNet.Common;
using LearnNet.CodeHelper;
using System.IO;
using System.Xml;

namespace SQLTools
{
    public partial class TempletCreate : Form
    {
        public TempletCreate()
        {
            InitializeComponent();
        }
      

        private NVelocityHelper nvHelper = null; //生成模板类
        //LTP.CodeBuild.CodeBuilders cb;//代码生成对象
        LearnNet.IDBO.IDbScriptBuilder dsb;
        LearnNet.IDBO.IDbObject dbobj;
        LearnNet.CmConfig.DbSettings dbset;//服务器配置
        string DbName = "master";
        Thread mythread;
        protected string configPath = "";

        protected List<TableInfo> tableInfos = null;

        public TempletCreate(string longservername, string dbname)
		{
            InitializeComponent();	
			DbName=dbname;
            dbset = LearnNet.CmConfig.DbConfig.GetSetting(longservername);
            dbobj = LearnNet.DBFactory.DBOMaker.CreateDbObj(dbset.DbType);
            dbobj.DbConnectStr = dbset.ConnectStr;  
            //cb = new LearnNet.CodeBuild.CodeBuilders(dbobj);
            dsb = LearnNet.DBFactory.DBOMaker.CreateScript(dbset.DbType);// ObjHelper.CreatDsb(longservername);

            this.lblServer.Text = dbset.Server;            
		}
        private void TempletCreate_Load(object sender, EventArgs e)
        {

            configPath = string.Concat(AppDomain.CurrentDomain.BaseDirectory, "/", "config.xml");
            XmlHelper xmlhelper = new XmlHelper(configPath, true);
            if (!xmlhelper.ExistNode(@"root/TempletCreate"))
            {
                xmlhelper.InsertElement("root", "TempletCreate", "", false);
                xmlhelper.Save();
            }
            else
            {
                tbCreatePath.Text = xmlhelper.GetText(@"root/TempletCreate/CreatePath");
                tbTempletPath.Text = xmlhelper.GetText(@"root/TempletCreate/TempletPath");
            }

            xmlhelper.Dispose();
            string mastedb = "master";
            switch (dbobj.DbType)
            {
                case "SQL2000":
                case "SQL2005":
                    mastedb = "master";
                    break;
                case "Oracle":
                case "OleDb":
                    mastedb = dbset.DbName;
                    break;
                case "MySQL":
                    mastedb = "mysql";
                    break;
            }
            if ((dbset.DbName == "") || (dbset.DbName == mastedb))
            {
                List<string> dblist = dbobj.GetDBList();
                if (dblist != null)
                {
                    if (dblist.Count > 0)
                    {
                        foreach (string dbname in dblist)
                        {
                            this.cmbDB.Items.Add(dbname);
                        }
                    }
                }
            }
            else
            {
                this.cmbDB.Items.Add(DbName);
            }
            this.btn_Creat.Enabled = false;
            this.cmbDB.Text = DbName;
        }
        #region 异步线程调用方法
        /// <summary>
        /// 异步线程调用方法更改文本框值
        /// </summary>
        /// <param name="txt"></param>
        delegate void delegateRefreshStatus(string txt,TextBox tb);
        /// <summary>
        /// 更改文本框值
        /// </summary>
        /// <param name="txt"></param>
        /// <param name="tb"></param>
        private void RefreshStatus(string txt, TextBox tb)
        {
            try
            {
                if (this.InvokeRequired)
                {
                    this.BeginInvoke(new delegateRefreshStatus(RefreshStatus), txt,tb);
                }
                else
                {
                    tb.Text = txt;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("更新界面状态时发生异常：" + ex.Message, "异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
                
            }
        }

        delegate string delegateGetTextBoxValue(TextBox tb);
        private string getTextBoxValue(TextBox tb)
        {
            try
            {
                if (this.InvokeRequired)
                {
                    return this.Invoke(new delegateGetTextBoxValue(getTextBoxValue), tb) as string; 
                
                }
                else
                {
                    return tb.Text;
                }
               
            }
            catch (Exception ex)
            {
                MessageBox.Show("获取界面值时发生异常：" + ex.Message, "异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return "";

            }
        }
        #endregion 
        private void cmbDB_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			string dbname= cmbDB.Text;
            List<string> tabNames = dbobj.GetTables(dbname);

			this.listTable1.Items.Clear();
			this.listTable2.Items.Clear();
            if (tabNames.Count > 0)
            {
                foreach (string tabname in tabNames)
                {
                    listTable1.Items.Add(tabname);
                }
            }
			
			IsHasItem();			
		}

		#region 按钮操作

        private void templetPath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
            XmlHelper xmlhelper = new XmlHelper(configPath, true);
            if (xmlhelper.ExistNode("root/TempletCreate/TempletPath"))
            {
                folderBrowserDialog1.SelectedPath = xmlhelper.GetText("root/TempletCreate/TempletPath");
            }
           
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                tbTempletPath.Text = folderBrowserDialog1.SelectedPath;
            }

       
            
            if (!xmlhelper.ExistNode(@"root/TempletCreate"))
            {
                xmlhelper.InsertElement("root", "TempletCreate", "", false);
            }
            if (!xmlhelper.ExistNode(@"root/TempletCreate/TempletPath"))
            {
                xmlhelper.InsertElement(@"root/TempletCreate", "TempletPath", tbTempletPath.Text, true);
            }
            else
            {
                xmlhelper.Update(@"root/TempletCreate/TempletPath", tbTempletPath.Text, true);
            }
            xmlhelper.Save();
            xmlhelper.Dispose();
            
        }

        private void btnCreatePath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
              XmlHelper xmlhelper = new XmlHelper(configPath,true);

              if (xmlhelper.ExistNode("root/TempletCreate/CreatePath"))
            {
                folderBrowserDialog1.SelectedPath = xmlhelper.GetText("root/TempletCreate/CreatePath");
            }
              if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
              {
                  tbCreatePath.Text = folderBrowserDialog1.SelectedPath;
              }
            if (!xmlhelper.ExistNode(@"root/TempletCreate"))
            {
                xmlhelper.InsertElement("root", "TempletCreate", "", false);
            }
            if (!xmlhelper.ExistNode(@"root/TempletCreate/CreatePath"))
            {
                xmlhelper.InsertElement(@"root/TempletCreate", "CreatePath", tbCreatePath.Text, true);
            }
            else
            {
                xmlhelper.Update(@"root/TempletCreate/CreatePath", tbCreatePath.Text, true);
            }
            xmlhelper.Save();
            xmlhelper.Dispose();
        }


		private void btn_Addlist_Click(object sender, System.EventArgs e)
		{
			int c=this.listTable1.Items.Count;
			for(int i=0;i<c;i++)
			{
				this.listTable2.Items.Add(this.listTable1.Items[i]);
			}
			this.listTable1.Items.Clear();

			IsHasItem();
		}

		private void btn_Add_Click(object sender, System.EventArgs e)
		{
		
			int c=this.listTable1.SelectedItems.Count;			
			ListBox.SelectedObjectCollection objs=this.listTable1.SelectedItems;
			for(int i=0;i<c;i++)
			{
				this.listTable2.Items.Add(listTable1.SelectedItems[i]);
				
			}
			for(int i=0;i<c;i++)
			{
				if(this.listTable1.SelectedItems.Count>0)
				{
					this.listTable1.Items.Remove(listTable1.SelectedItems[0]);
				}
			}
			IsHasItem();
		}

		private void btn_Del_Click(object sender, System.EventArgs e)
		{
			int c=this.listTable2.SelectedItems.Count;			
			ListBox.SelectedObjectCollection objs=this.listTable2.SelectedItems;
			for(int i=0;i<c;i++)
			{
				this.listTable1.Items.Add(listTable2.SelectedItems[i]);
				
			}
			for(int i=0;i<c;i++)
			{
				if(this.listTable2.SelectedItems.Count>0)
				{
					this.listTable2.Items.Remove(listTable2.SelectedItems[0]);
				}
			}
		
			IsHasItem();
		}

		private void btn_Dellist_Click(object sender, System.EventArgs e)
		{
			int c=this.listTable2.Items.Count;
			for(int i=0;i<c;i++)
			{
				this.listTable1.Items.Add(this.listTable2.Items[i]);
			}
			this.listTable2.Items.Clear();
			IsHasItem();			
		}
		#endregion

		#region listbox操作
		private void listTable1_DoubleClick(object sender, System.EventArgs e)
		{
			if(this.listTable1.SelectedItem!=null)
			{
				this.listTable2.Items.Add(listTable1.SelectedItem);
				this.listTable1.Items.Remove(this.listTable1.SelectedItem);
				IsHasItem();
			}
		}

		private void listTable2_DoubleClick(object sender, System.EventArgs e)
		{		
			if(this.listTable2.SelectedItem!=null)
			{
				this.listTable1.Items.Add(listTable2.SelectedItem);
				this.listTable2.Items.Remove(this.listTable2.SelectedItem);
				IsHasItem();
			}
		}

		/// <summary>
		/// 判断listbox有没有项目
		/// </summary>
		private void IsHasItem()
		{
			if(this.listTable1.Items.Count>0)
			{
				this.btn_Add.Enabled=true;
				this.btn_Addlist.Enabled=true;
			}
			else
			{
				this.btn_Add.Enabled=false;
				this.btn_Addlist.Enabled=false;
			}
			if(this.listTable2.Items.Count>0)
			{
				this.btn_Del.Enabled=true;
				this.btn_Dellist.Enabled=true;	
				this.btn_Creat.Enabled=true;
			}
			else
			{
				this.btn_Del.Enabled=false;
				this.btn_Dellist.Enabled=false;	
				this.btn_Creat.Enabled=false;
			}
		}
		

		private void btn_Cancle_Click(object sender, System.EventArgs e)
		{		
			
			if((mythread!=null)&&(mythread.IsAlive))
			{
				mythread.Abort();
			}
			this.Close();
		}
		private void btn_Creat_Click(object sender, System.EventArgs e)
		{		
			try
			{
                if (this.tbTempletPath.Text == "")
                {
                    MessageBox.Show("请选择模板路径！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
				if(this.tbCreatePath.Text=="")
				{
                    MessageBox.Show("请选择保存文件路径！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
					return;
				}
               
				mythread = new Thread(new ThreadStart(ThreadWork));
				mythread.Start();
			}
			catch(System.Exception ex)
			{
                LogInfo.WriteLog(ex);
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Stop);
			}
        }
        #endregion

        void ThreadWork()
        {
            try
            {
                this.Text = "正在生成页面...";
                this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
                this.btn_Creat.Enabled = false;
                this.btn_Cancle.Enabled = false;
                string dbname = this.cmbDB.Text;
                string strtitle = "数据库名：" + dbname;
                int tblCount = this.listTable2.Items.Count;

                string filename = this.tbTempletPath.Text;
              
                this.labelNum.Text = "0";

                #region 循环每个表
                TableInfo tableInfo = null;
                tableInfos = new List<TableInfo>();
                for (int i = 0; i < tblCount; i++)
                {
                    this.listTable2.SelectedIndex = i;
                    string tablename = this.listTable2.Items[i].ToString();
                    tableInfo = dbobj.GetTablesInfo(dbname, tablename);
                    if (tableInfo != null)
                    {
                        tableInfo.ColumnInfos = dbobj.GetColumnList(dbname, tablename);
                        tableInfos.Add(tableInfo);
                        
                    }
                  
                    this.labelNum.Text = (i + 1).ToString();
                }
               
                #endregion
                if (ckbCreateFolderByTable.Checked)
                {
                    CreateTempletFolderByTableName(tableInfos);
                }
                if (ckbCreateFileByTableName.Checked)
                {
                    CreateTempletFileByTableName(tableInfos);
                }
                if(!ckbCreateFileByTableName.Checked && !ckbCreateFolderByTable.Checked)
                {
                    if (CreatTemplet(tableInfos))
                    {
                        MessageBox.Show("模板全部生成成功！", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                this.Cursor = System.Windows.Forms.Cursors.Default;
                this.Text = "模板生成完成！";
              
                this.btn_Creat.Enabled = true;
                this.btn_Cancle.Enabled = true;
            }
            catch (System.Exception ex)
            {
                LogInfo.WriteLog(ex);
                this.btn_Creat.Enabled = true;
                this.btn_Cancle.Enabled = true;
                this.Text = "模板生成失败！";
                this.Cursor = System.Windows.Forms.Cursors.Default;
                MessageBox.Show("模板生成失败！(" + ex.Message + ")", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        /// <summary>
        /// 根据table名称生成到不同文件
        /// </summary>
        /// <param name="tabs"></param>
        private void CreateTempletFileByTableName(List<TableInfo> tabs)
        {
            nvHelper = new NVelocityHelper(getTextBoxValue(tbTempletPath));
            progressBar2.Maximum = tabs.Count;
            progressBar2.Value = 0;
            List<TableInfo> tableTemps = null;
            string strTempsPath = getTextBoxValue(tbTempletPath);
            if (!Directory.Exists(strTempsPath))
            {
                MessageBox.Show("模板生成失败！请检查模板路径是否正确。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            for (int i = 0; i < tabs.Count; i++)
            {
                tableTemps = new List<TableInfo>();
                tableTemps.Add(tabs[i]);
                nvHelper.RemoveAll();
                nvHelper.Put("TableInfos", tableTemps);

                DirectoryInfo fdir = new DirectoryInfo(strTempsPath);
                FileInfo[] files = fdir.GetFiles();
                string strCreatePath = getTextBoxValue(tbCreatePath);
                if (!Directory.Exists(strCreatePath))
                {
                    Directory.CreateDirectory(strCreatePath);
                }
                this.progressBar1.Maximum = files.Length;
                progressBar1.Value = 0;
                string path = "";
                foreach (FileInfo file in files)
                {
                    path = string.Concat(strCreatePath, "\\", tabs[i].TabName, file.Name);
                    File.Delete(path);
                    LearnNet.Common.Utils.CreateTextFile(path, nvHelper.Display(file.Name).ToString());
                   
                    progressBar1.Value = progressBar1.Value + 1;
                }
                progressBar2.Value = progressBar2.Value + 1;

            }
            MessageBox.Show("模板全部生成成功！", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }

        /// <summary>
        /// 根据table名不同生成到相应文件夹下面
        /// </summary>
        /// <param name="tabs"></param>
        private void CreateTempletFolderByTableName(List<TableInfo> tabs)
        {
            nvHelper = new NVelocityHelper(getTextBoxValue(tbTempletPath));
            progressBar2.Maximum = tabs.Count;
            progressBar2.Value = 0;
            List<TableInfo> tableTemps = null;
            string strTempsPath = getTextBoxValue(tbTempletPath);
            if (!Directory.Exists(strTempsPath))
            {
                MessageBox.Show("模板生成失败！请检查模板路径是否正确。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            for (int i = 0; i < tabs.Count; i++)
            {
                tableTemps = new List<TableInfo>();
                tableTemps.Add(tabs[i]);
                nvHelper.RemoveAll();
                nvHelper.Put("TableInfos", tableTemps);

                DirectoryInfo fdir = new DirectoryInfo(strTempsPath);
                FileInfo[] files = fdir.GetFiles();
                string strCreatePath = string.Concat(getTextBoxValue(tbCreatePath), "\\", tabs[i].TabName);
                if (!Directory.Exists(strCreatePath))
                {
                    Directory.CreateDirectory(strCreatePath);
                }
                this.progressBar1.Maximum = files.Length;
                progressBar1.Value = 0;
                string path = "";
                foreach (FileInfo file in files)
                {
                    path = string.Concat(strCreatePath, "\\", file.Name);
                    File.Delete(path);
                    LearnNet.Common.Utils.CreateTextFile(path, nvHelper.Display(file.Name).ToString());
                    progressBar1.Value = progressBar1.Value + 1;
                }
                progressBar2.Value = progressBar2.Value + 1;

            }
            MessageBox.Show("模板全部生成成功！", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }

        private bool CreatTemplet(List<TableInfo> tabs)
        {
            if (!Directory.Exists(getTextBoxValue(tbTempletPath)))
            {
                MessageBox.Show("模板生成失败！请检查模板路径是否正确。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            nvHelper = new NVelocityHelper(getTextBoxValue(tbTempletPath));
           
            nvHelper.RemoveAll();
            nvHelper.Put("TableInfos", tabs);
           
          
            DirectoryInfo fdir = new DirectoryInfo(getTextBoxValue( tbTempletPath));
            FileInfo[] files = fdir.GetFiles();
            this.progressBar1.Maximum = files.Length;
            progressBar1.Value = 0;
            string strCreatePath = getTextBoxValue(tbCreatePath);
            if (!Directory.Exists(strCreatePath))
            {
                Directory.CreateDirectory(strCreatePath);
            }
            string path="";
            foreach (FileInfo file in files)
            {
                path=string.Concat(strCreatePath ,"\\", file.Name);
                File.Delete(path);
                LearnNet.Common.Utils.CreateTextFile(path, nvHelper.Display(file.Name).ToString());
                progressBar1.Value = progressBar1.Value + 1;
            }
            return true;
           
        }

     



    }
}
